<script setup lang="ts">
import { getOrderCodeDetail, getOrderCodeList } from "@/api/stock/putStock";
import { useUserStoreHook } from "@/store/modules/user";
import { dealDataRide } from "@/utils/common";
import { message } from "@/utils/message";
import { onMounted, ref } from "vue";
import { useColumns } from "./columns";
const { orderColumns, goodsColumns } = useColumns();

const props = defineProps({
  subOrderId: {
    type: Number,
    default: 0
  },
  // 	配货单类型 1 仓库 2 供应商
  distributionType: {
    type: Number,
    default: 2
  }
});

const submitForm = ref({
  orderIndex: ""
});
const tableRef = ref();
const goodsList = ref([]);
const tableSelectList = ref([]);

const loadOrder = ref(false);
const orderCodeList = ref<any>([]);
const showOrderList = ref([]);

// 选择商品
function handleSelectionChange(val) {
  tableSelectList.value = val;
}

// 获取出库单列表
const loadOrderList = async () => {
  loadOrder.value = true;

  let { data } = await getOrderCodeList();
  orderCodeList.value = data || [];

  setTimeout(() => {
    loadOrder.value = false;
  }, 200);
};

const chooseChange = async index => {
  let orderCode = orderCodeList.value[index];

  // 根据code查询订单详情
  let { data } = await getOrderCodeDetail({ storeOrderCode: orderCode });
  if (data) {
    showOrderList.value = [data];
    goodsList.value = data.putInItemResponses || [];
  } else {
    showOrderList.value = [];
    goodsList.value = [];
  }
};

const getOrderTypeText = orderNo => {
  let str = "门店采购";
  if (orderNo.indexOf("KD") != -1) {
    str = "跨店销售";
  }
  return str;
};

onMounted(() => {
  loadOrderList();
});

// 确认入库
const confirmPut = () => {
  return new Promise(resolve => {
    let obj = {
      isPass: false,
      params: {}
    };

    if (goodsList.value.length == 0) {
      message("请选择入库订单", { type: "warning" });
      return obj;
    }

    let filterList = goodsList.value.filter(
      v => v.stockCount && v.stockCount !== 0
    );
    if (filterList.length == 0) {
      message("未填写入库数量", { type: "warning" });
      return obj;
    }
    // for (let index = 0; index < goodsList.value.length; index++) {
    //   const v = goodsList.value[index];
    //   if (!v.stockCount) {
    //     message(`'${v.goodsName}' 未填写入库数量`, { type: "warning" });
    //     return obj;
    //   }
    // }

    let params = {
      storeId: useUserStoreHook().loginStoreId,
      storeOrderCode: orderCodeList.value[submitForm.value.orderIndex],
      putInItemRequests: filterList.map(v => {
        return {
          goodsId: v.goodsId,
          putInNum: v.stockCount,
          putInPrice: dealDataRide(v.stockCount, v.buyPrice),
          specCode: v.specCode,
          suborderId: v.suborderId
        };
      })
    };
    obj.isPass = true;
    obj.params = params;
    resolve(obj);
  });
};

defineExpose({ confirmPut });
</script>

<template>
  <div class="goods-table">
    <!-- 订单信息 -->
    <div class="mb-5">
      <h3 class="text-black mb-3">订单信息</h3>
      <el-form
        ref="formRef"
        label-position="right"
        label-width="110"
        :model="submitForm"
        class="w-[450px]"
      >
        <el-form-item label="业务订单编号" prop="orderIndex" required>
          <el-select
            v-model="submitForm.orderIndex"
            v-loading="loadOrder"
            filterable
            placeholder="请选择"
            @change="chooseChange"
          >
            <el-option
              v-for="(item, index) in orderCodeList"
              :key="index"
              :label="item"
              :value="index"
            >
              <div class="flex items-center justify-between">
                <div>{{ item }}</div>
                <el-tag
                  class="ml-1"
                  :type="item.indexOf('KD') != -1 ? 'warning' : 'success'"
                  size="small"
                  >{{ getOrderTypeText(item) }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="w-[80%]">
        <pure-table
          ref="tableRef"
          row-key="id"
          align-whole="center"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          max-height="500"
          :data="showOrderList"
          :columns="orderColumns"
          @selection-change="handleSelectionChange"
        />
      </div>
    </div>

    <!-- 商品明细 -->
    <div class="mb-5">
      <h3 class="text-black mb-3">商品明细</h3>
      <pure-table
        ref="tableRef"
        row-key="id"
        align-whole="center"
        :header-cell-style="{
          background: 'var(--el-fill-color-light)',
          color: 'var(--el-text-color-primary)'
        }"
        max-height="500"
        :data="goodsList"
        :columns="goodsColumns"
        @selection-change="handleSelectionChange"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.goods-table {
  padding: 0 20px;
  margin-bottom: 25px;
  min-height: 500px;
}
.tips {
  display: flex;
  align-items: center;
  padding: 6px 15px;
  border: 1px solid #c6e2ff;
  border-radius: 5px;
  background-color: #ecf5ff;
}
</style>
